from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.db.models import F
from .models import *
from .serializers import *
from user_app.utils import *
from user_app.models import User
from subjects_app.models import Subject  # 导入Subject模型
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema

class ExaminationQuestionsView(generics.RetrieveAPIView):
    """
    获取题目详情
    """
    queryset = ExaminationQuestions.objects.all()
    serializer_class = ExaminationQuestionsSerializer
    
    @swagger_auto_schema(
        operation_summary="获取题目详情",
        operation_description="根据题目ID获取单个题目的详细信息",
        manual_parameters=[
            openapi.Parameter(
                'pk', openapi.IN_PATH,
                description="题目ID",
                type=openapi.TYPE_INTEGER
            )
        ],
        responses={
            200: openapi.Response(
                description="获取题目详情成功",
                schema=ExaminationQuestionsSerializer
            ),
            404: openapi.Response(description="题目不存在")
        }
    )
    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)


class RandomQuestionView(APIView):
    """
    随机获取一个未回答的题目
    """
    @swagger_auto_schema(
        operation_summary="随机获取题目",
        operation_description="随机获取一个题目，可以选择排除已回答的题目",
        manual_parameters=[
            openapi.Parameter(
                'Authorization', openapi.IN_HEADER,
                description="认证token，格式：Bearer {token}",
                type=openapi.TYPE_STRING,
                required=True
            ),
            openapi.Parameter(
                'exclude_answered', openapi.IN_QUERY,
                description="是否排除已回答的题目，true/false，默认为false",
                type=openapi.TYPE_BOOLEAN
            )
        ],
        responses={
            200: openapi.Response(
                description="随机获取题目成功",
                schema=ExaminationQuestionsSerializer
            ),
            401: openapi.Response(description="未授权，请提供有效的token"),
            404: openapi.Response(description="暂无可用题目")
        }
    )
    def get(self, request):
        data = verify_token(request.META.get("HTTP_AUTHORIZATION"))
        if not data:
            return Response({"message": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
        try:
            user = User.objects.get(id=data["id"])
        except User.DoesNotExist:
            return Response({"message": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)
        
        exclude_answered = request.query_params.get('exclude_answered', 'false').lower() == 'true'
        
        if exclude_answered:
            answered_ids = UserAnswerRecord.objects.filter(user=user).values_list('question_id', flat=True)
            questions = ExaminationQuestions.objects.exclude(id__in=answered_ids).order_by('?')
        else:
            questions = ExaminationQuestions.objects.all().order_by('?')
        
        question = questions.first()
        if not question:
            return Response({"message": "暂无可用题目"}, status=status.HTTP_404_NOT_FOUND)
        
        serializer = ExaminationQuestionsSerializer(question)
        return Response(serializer.data, status=status.HTTP_200_OK)

class UserAnswersRecordAddView(APIView):
    """
    批量记录用户的答案，如果已有记录则更新记录
    """
    @swagger_auto_schema(
        operation_summary="批量记录用户答案",
        operation_description="批量记录用户的答题情况，如果已有记录则更新",
        manual_parameters=[
            openapi.Parameter(
                'Authorization', openapi.IN_HEADER,
                description="认证token，格式：Bearer {token}",
                type=openapi.TYPE_STRING,
                required=True
            )
        ],
        request_body=openapi.Schema(
            type=openapi.TYPE_ARRAY,
            items=openapi.Schema(
                type=openapi.TYPE_OBJECT,
                required=['question', 'answer'],
                properties={
                    'question': openapi.Schema(type=openapi.TYPE_INTEGER, description='题目ID'),
                    'answer': openapi.Schema(type=openapi.TYPE_STRING, description='用户答案')
                }
            )
        ),
        responses={
            200: openapi.Response(
                description="批量记录答案成功",
                schema=openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        'message': openapi.Schema(type=openapi.TYPE_STRING, description='成功消息')
                    }
                )
            ),
            400: openapi.Response(description="参数错误"),
            401: openapi.Response(description="未授权，请提供有效的token")
        }
    )
    def post(self, request):
        serializer = UserAnswersRecordAddSerializer(data=request.data)
        if serializer.is_valid():
            data = verify_token(request.META.get("HTTP_AUTHORIZATION"))
            user = User.objects.get(id=data["id"])
            for validated_data in serializer.validated_data:
                record = UserAnswerRecord.objects.filter(user=user, question_id=validated_data["question"]).first()
                if record:
                    record.answer = validated_data["answer"]
                    record.save()
                else:
                    question = ExaminationQuestions.objects.get(id=validated_data["question"])
                    answer = validated_data["answer"]
                    UserAnswerRecord.objects.create(user=user, question=question, answer=answer)
            return Response({"message": "试卷答案添加成功"}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
class UserAnswerRecordAddView(APIView):
    """
    添加用户回答记录，如果已有记录则更新记录
    """
    @swagger_auto_schema(
        operation_summary="添加单条用户答案",
        operation_description="添加单条用户的答题情况，如果已有记录则更新",
        manual_parameters=[
            openapi.Parameter(
                'Authorization', openapi.IN_HEADER,
                description="认证token，格式：Bearer {token}",
                type=openapi.TYPE_STRING,
                required=True
            )
        ],
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['question', 'answer'],
            properties={
                'question': openapi.Schema(type=openapi.TYPE_INTEGER, description='题目ID'),
                'answer': openapi.Schema(type=openapi.TYPE_STRING, description='用户答案')
            }
        ),
        responses={
            200: openapi.Response(
                description="添加/更新答案记录成功",
                schema=openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        'message': openapi.Schema(type=openapi.TYPE_STRING, description='成功消息')
                    }
                )
            ),
            400: openapi.Response(description="参数错误"),
            401: openapi.Response(description="未授权，请提供有效的token")
        }
    )
    def post(self, request):
        serializer = UserAnswerRecordAddSerializer(data=request.data)
        if serializer.is_valid():
            data = verify_token(request.META.get("HTTP_AUTHORIZATION"))
            user = User.objects.get(id=data["id"])
            # 检查是否已存在记录
            record = UserAnswerRecord.objects.filter(user=user, question_id=serializer.validated_data["question"]).first()
            if record:
                # 更新记录
                record.answer = serializer.validated_data["answer"]
                record.save()
                return Response({"message": "回答记录更新成功"}, status=status.HTTP_200_OK)
            # 如果不存在记录，则创建新记录
            question = ExaminationQuestions.objects.get(id=serializer.validated_data["question"])
            answer = serializer.validated_data["answer"]
            UserAnswerRecord.objects.create(user=user, question=question, answer=answer)
            return Response({"message": "回答记录添加成功"}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



class QuestionsBySourceView(APIView):
    """
    根据科目获取题目
    """
    serializer_class = ExaminationQuestionsSerializer
    
    @swagger_auto_schema(
        operation_summary="根据科目获取题目",
        operation_description="根据科目ID获取该科目的所有题目列表",
        manual_parameters=[
            openapi.Parameter(
                'subject_id', openapi.IN_QUERY,
                description="科目ID",
                type=openapi.TYPE_INTEGER,
                required=True
            )
        ],
        responses={
            200: openapi.Response(
                description="获取题目列表成功",
                schema=ExaminationQuestionsSerializer(many=True)
            ),
            400: openapi.Response(description="缺少subject_id参数"),
            404: openapi.Response(description="科目不存在")
        }
    )
    def get(self, request):
        try:
            subject_id = request.query_params.get('subject_id')
            if not subject_id:
                return Response({"message": "缺少subject_id参数"}, status=status.HTTP_400_BAD_REQUEST)
            questions = ExaminationQuestions.objects.filter(question_source=subject_id)
            serializer = self.serializer_class(questions, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except Subject.DoesNotExist:
            return Response({"message": "科目不存在"}, status=status.HTTP_404_NOT_FOUND)

###错题查询
class WrongQuestionsView(APIView):
    """
    获取用户答错的题目
    """
    @swagger_auto_schema(
        operation_summary="获取错题集",
        operation_description="获取当前登录用户答错的题目列表",
        manual_parameters=[
            openapi.Parameter(
                'Authorization', openapi.IN_HEADER,
                description="认证token，格式：Bearer {token}",
                type=openapi.TYPE_STRING,
                required=True
            )
        ],
        responses={
            200: openapi.Response(
                description="获取错题集成功",
                schema=UserAnswerRecordSerializer(many=True)
            ),
            401: openapi.Response(description="未授权，请提供有效的token"),
            404: openapi.Response(description="用户不存在")
        }
    )
    def get(self, request):
        data = verify_token(request.META.get("HTTP_AUTHORIZATION"))
        if not data:
            return Response({"message": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
        try:
            user = User.objects.get(id=data["id"])
        except User.DoesNotExist:
            return Response({"message": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)
        # 获取用户答错的题目,查询用户的答案，根据question这个外键在ExaminationQuestions中查找对应题目的答案，返回答案不相符的错题集
        wrong_questions = UserAnswerRecord.objects.filter(user=user).exclude(answer=F('question__answer')).select_related('question')
        # 使用新的UserAnswerRecordSerializer替换ExaminationQuestionsSerializer
        serializer = UserAnswerRecordSerializer(wrong_questions, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

        

        